using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml;
using Microsoft.SharePoint.Utilities;


namespace ImageEnhancer
{

  public class PicturePicker : LayoutsPageBase {

    // add control fields to match controls tags on .aspx page
    //protected SPGridView grdSiteProperties;
      protected DropDownList dpdPictureLibraries;
      protected Button btnSubmit;
      protected Button btnCancel;
      protected Label lblMsg;
      private SPWeb web;
      string listId;
      //private SPListItem currentItem;
      SPList list;
      public static HttpContext GetContext()
      {
          return HttpContext.Current;
      }
      protected override void OnLoad(EventArgs e) {
   
    }
      protected override void OnUnload(EventArgs e)
      {
          /*base.OnUnload(e);
          //detach from the static SiteMapResolve event and restore localization mode
          SiteMap.Providers["SPXmlContentMapProvider"].EnableLocalization = true;
          SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve -=
          new SiteMapResolveEventHandler(provider_SiteMapResolve);*/
      } 

    protected override void OnInit(EventArgs e) {
        string strurl = Request.QueryString["siteId"];
        listId = Request["listId"];
        //strurl += "/_vti_bin/lists.asmx";
        XmlDocument bindtodd = SharepointInformation.GetListColletionXML(strurl, 109);
        if (!IsPostBack)
        {
            try
            {
                
                   
                dpdPictureLibraries.EnableViewState = true;
                SmartProvider dsprovider = new SmartProvider(bindtodd);
                if (bindtodd.FirstChild.ChildNodes.Count > 0)
                {

                    dpdPictureLibraries.DataTextField = bindtodd.FirstChild.ChildNodes.Item(0).Attributes[0].Name;
                    dpdPictureLibraries.DataValueField = bindtodd.FirstChild.ChildNodes.Item(0).Attributes[1].Name;
                    //dpdPictureLibraries.SelectedItem or value
                    dpdPictureLibraries.DataSource = dsprovider;

                    dpdPictureLibraries.DataBind();
                    string qsListId;
                    qsListId = listId.Replace('{', ' ').Trim();
                    qsListId = qsListId.Replace('}', ' ').Trim();
                    Guid _listGuid = new Guid(qsListId);
                    System.Collections.Specialized.NameValueCollection PictureLibrarys;
                    PictureLibrarys = SharepointInformation.QueryCustType(SPContext.Current.Web.Url.ToString(), _listGuid, "CustomImageStorage");
                    if (PictureLibrarys.Count <= 1) {
                        SPUtility.Redirect("listedit.aspx?List=" + listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
                    }
                    if (PictureLibrarys[0].Equals("True"))
                    {
                        //PictureLibrarys[1];este es el selected.
                        dpdPictureLibraries.SelectedIndex = dpdPictureLibraries.Items.IndexOf(dpdPictureLibraries.Items.FindByText(PictureLibrarys[2]));
                    }
                    else
                    {
                        ////NO PICTURE LIBRARY SELECTED YET
                        //SPUtility.Redirect("listedit.aspx?List=" + listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
                    }

                }
                else
                {
                    //THERE ARE NO PICTURE LIBRARYS IN THE SITE
                    SPUtility.Redirect("listedit.aspx?List=" + listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
                }
            }
            catch (Exception ex)
            {
                //yopur need to create a picture library within the site, if the problem persist please contact IT
                SPUtility.Redirect("listedit.aspx?List=" + listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
            }
        }
        else
        {
            EnsureChildControls();
        }
        btnSubmit.Click += new EventHandler(btnSubmit_OnClick);
        btnCancel.Click += new EventHandler(btnCancel_OnClick);
        //dpdPictureLibraries.SelectedIndexChanged += new EventHandler(dpdPictureLibraries_OnSelectedIndexChange);
      ////////////////////////////////////
        base.OnInit(e);
        SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve +=
        new SiteMapResolveEventHandler(provider_SiteMapResolve);
        
        string itemId = "1";//Request["itemId"];
        if (string.IsNullOrEmpty(listId) && string.IsNullOrEmpty(itemId))
        {
            throw new Exception("Invalid item ID or list ID.");
        }
        else
        {
            web = SPControl.GetContextWeb(Context);
            list = web.Lists.GetList(new Guid(listId), true);
                } 
        /////////////////////////////////
  
    }
    protected void dpdPictureLibraries_OnSelectedIndexChange(object sencer, EventArgs e) { 
        
    }
    protected void btnSubmit_OnClick(object sender, EventArgs e) {
        //lblMsg.Text = dpdPictureLibraries.SelectedValue;

        SharepointInformation.ListChangeProperty(Request.QueryString["siteId"], Request.QueryString["listId"],
            "ImageEnhancerCustomField", "CustomImageStorage", dpdPictureLibraries.SelectedItem.Text);
        SPUtility.Redirect("listedit.aspx?List=" + listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
    }
    protected void btnCancel_OnClick(object sender, EventArgs e)
    {
        //lblMsg.Text = dpdPictureLibraries.SelectedValue;
        SPUtility.Redirect("listedit.aspx?List="+listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
    }
    //list.ParentWebUrl + "/_layouts/listedit.aspx?List="+listId;
   
    protected override void OnPreInit(EventArgs e)
    {
        base.EnableViewState = true;
        base.OnPreInit(e);
    }
    protected override void TrackViewState()
    {
        
        base.TrackViewState();
    }
    /// <summary> 
    /// Determines whether the two contexts are equal and, therefore, 
    /// whether the SiteMap.SiteMapResolve event should be fired. 
    /// </summary> 
    protected virtual bool IsSamePage(HttpContext context1, HttpContext context2)
    {

        //by default, the contexts are considered the same if they 

        //map to the same file and the same listid/itemid 

        return ((Server.MapPath(context1.Request.AppRelativeCurrentExecutionFilePath) ==

                  Server.MapPath(context2.Request.AppRelativeCurrentExecutionFilePath)) &&

                  (context1.Request.QueryString == context2.Request.QueryString));

    }

    /// <summary> 
    /// Overrides the breadcrumbs with a new one in the format 
    /// [site]>[repository list]>[process folder]>[page title]. 
    /// </summary> 
    SiteMapNode provider_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
    {
        if (!IsSamePage(Context, e.Context) )
        {
            e.Provider.EnableLocalization = true;
            return e.Provider.CurrentNode;
        }
        SiteMapNode pageTitleNode;
        SiteMapNode listNode2;
        SiteMapNode listNode;
        string settings = "List Settings";
        try
        {
            // Trun off localization, so that the custom nodes do not get overwritten 

            e.Provider.EnableLocalization = false;

            // Clone some node to get a valid node object and modify it. 

            listNode2 = e.Provider.RootNode.ChildNodes[0].Clone();
            listNode2.Url = list.DefaultViewUrl;//currentItem.ParentList.DefaultViewUrl;
            listNode2.Title = list.Title;
            listNode2.ChildNodes = new SiteMapNodeCollection();
            
            listNode = e.Provider.RootNode.ChildNodes[0].Clone();
            listNode.Url = list.ParentWebUrl + "/_layouts/listedit.aspx?List="+listId;//currentItem.ParentList.DefaultViewUrl;
            listNode.Title = settings;
            listNode.ChildNodes = new SiteMapNodeCollection();
            listNode.ParentNode =listNode2;
            
            //Another node



            // Add as many new nodes as you need here 

            pageTitleNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());

            pageTitleNode.Title = "Picture library selector";//Title.Text;

            listNode.ChildNodes.Add(pageTitleNode);
            //
            pageTitleNode.ParentNode = listNode;

        }

        catch (Exception ex)
        {

            return e.Provider.CurrentNode;

        }

        return pageTitleNode;

    }

    
  }
}
